import { computed, ref } from "vue";
import { defineStore } from "pinia";

const USER_KEY = "OA_USER_KEY";
const TOKEN_KEY = "OA_TOKEN_KEY";

export const PermissionChoices = {
  All: 0b111,
  Staff: 0b000, //员工权限
  Boarder: 0b001, //董事会权限
  Leader: 0b010, //部门经理权限
};

export const useAuthStore = defineStore("counter", () => {
  let _user = ref({});
  let _token = ref("");

  function setUserToken(user, token) {
    // save in memory
    _user.value = user;
    _token.value = token;

    // save in local storage
    localStorage.setItem(USER_KEY, JSON.stringify(user));
    localStorage.setItem(TOKEN_KEY, token);
  }

  let user = computed(() => {
    if (Object.keys(_user.value) == 0) {
      let user_str = localStorage.getItem(USER_KEY);
      if (user_str) _user.value = JSON.parse(user_str);
    }
    return _user.value;
  });

  let token = computed(() => {
    if (!_token.value) {
      let token_str = localStorage.getItem(TOKEN_KEY);
      if (token_str) _token.value = token_str;
    }
    return _token.value;
  });

  let is_logined = computed(() => {
    return Object.keys(user.value).length > 0 && token.value.length > 0;
  });

  function logout() {
    _user.value = {};
    _token.value = "";
    localStorage.removeItem(USER_KEY);
    localStorage.removeItem(TOKEN_KEY);
  }

  let own_permission = computed(() => {
    let permission_code = PermissionChoices.Staff;
    if (is_logined.value) {
      if (user.value.department == "董事会") {
        permission_code |= PermissionChoices.Boarder;
      }
      if (user.value.department.leader == user.value.uid) {
        permission_code |= PermissionChoices.Leader;
      }
    }
    return permission_code;
  });

  const has_permission = (permission_code, opt = "|") => {
    let result = permission_code.map(
      (permission) => (permission & own_permission.value) == permission
    );
    if (opt == "|") {
      return result.indexOf(true) >= 0;
    } else {
      return result.indexOf(false) >= 0;
    }
  };

  return { setUserToken, user, token, is_logined, logout, has_permission };
});
